package com.yowasa.xiuxian.engine.callback.map;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.yowasa.xiuxian.annoations.Item;
import com.yowasa.xiuxian.annoations.NOTIFY;
import com.yowasa.xiuxian.controller.MainController;
import com.yowasa.xiuxian.engine.BattleEngine;
import com.yowasa.xiuxian.engine.HoneEngine;
import com.yowasa.xiuxian.engine.callback.CmdCallBackHandler;
import com.yowasa.xiuxian.engine.hone.MentalInterface;
import com.yowasa.xiuxian.entity.bo.battle.BattleContent;
import com.yowasa.xiuxian.entity.bo.user.UserBO;
import com.yowasa.xiuxian.entity.mys.ClickMsgComponent;
import com.yowasa.xiuxian.entity.mys.MysComponent;
import com.yowasa.xiuxian.entity.mys.SendMessage;
import com.yowasa.xiuxian.entity.po.XiuXianExploreResource;
import com.yowasa.xiuxian.entity.po.XiuXianExploreUser;
import com.yowasa.xiuxian.entity.po.XiuxianMapInfoPO;
import com.yowasa.xiuxian.service.helper.*;
import com.yowasa.xiuxian.util.ComponentUtil;
import com.yowasa.xiuxian.util.RandomUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@NOTIFY(tag = "探索资源")
public class ExploreItemHandler extends CmdCallBackHandler {
    public static final Logger logger = LoggerFactory.getLogger(ExploreItemHandler.class);

    @Autowired
    private MessageHelper messageHelper;

    @Autowired
    private ExploreHelper exploreHelper;

    @Autowired
    private UserHelper userHelper;

    @Autowired
    private BattleEngine battleEngine;

    @Autowired
    private BattleHelper battleHelper;

    @Autowired
    private ItemHelper itemHelper;

    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED)
    public void execute(ClickMsgComponent message) {
        SendMessage sendMessage = new SendMessage();
        sendMessage.setRoom_id(message.getRoom_id());
        sendMessage.setVilla_id(message.getVilla_id());
        String uid = message.getUid();
        sendMessage.setFrom_user_id(uid);
        JSONObject jsonObject = JSONUtil.parseObj(message.getExtra());

        Integer mapId = jsonObject.getInt("mapId");
        Integer resourceId = jsonObject.getInt("resourceId");

        UserBO userBO = userHelper.checkOpUserAndState(sendMessage);
        XiuXianExploreUser exploreUser = exploreHelper.selectUser(userBO.getId());
        XiuXianExploreResource xiuXianExploreResource = exploreHelper.checkResource(mapId, resourceId, exploreUser);
        Boolean flag = true;
        Integer days = RandomUtil.randomInt(1,4);
        StringBuffer sb = new StringBuffer();
        sb.append("你花费了").append(days).append("天前往资源地点\n");
        logger.info("查询出来的资源为：{}",xiuXianExploreResource);
        if(xiuXianExploreResource.getType() == 1){
            //怪物资源
            Integer exploreMap = exploreUser.getExploreMap() - 20;
            Integer i = RandomUtil.randomInt(1, 3) + exploreMap;
            i = i > 9 ? 9 : i;

            UserBO bo = userHelper.initUser(xiuXianExploreResource.getResourceName());
            bo.setAge(RandomUtil.randomInt(30, 400));
            bo.getUserConfig().setMental("稻妻怪物");
            MentalInterface mental = HoneEngine.mentalMap.get(bo.getUserConfig().getMental());
            bo.setUserId("enemy0"+i);
            bo.getUserConfig().getBattleStrategyList().addAll(Arrays.asList(xiuXianExploreResource.getSkills().split(",").clone()));
            for (int a = 1; a < 9; a++) {
                bo.setLevel(100);
                mental.breakUp(bo);
                userHelper.rebuildBattleInfo(bo);
                bo.buildBaseInfo();
            }
            bo.getUserBattle().setHp(bo.getUserBattle().getHp() + 5000);
            bo.getUserBattle().setChp(bo.getUserBattle().getChp() + 5000);
            bo.getUserBattle().setDef(bo.getUserBattle().getDef() + 2000);
            bo.getUserBattle().setRes(bo.getUserBattle().getRes() + 2000);
            bo.getUserBattle().setSpd(bo.getUserBattle().getSpd() + 3000);
            //战斗
            BattleContent content = battleEngine.battle(userBO, bo);
            //战斗时长
            int days1 = battleHelper.calCostTime(content) + 1;
            days += days1;
            sb.append("你花费了").append(days1).append("天，与 [").append(xiuXianExploreResource.getResourceName()).append("]战斗\n");
            battleHelper.syncUserState(content);
            exploreHelper.lockUser(exploreUser, days, userBO.getName() + "正在战斗中");
            if (content.getResult() != 1) {
                flag = false;
            }
            String msg = content.getMsgLog().stream().collect(Collectors.joining("\n"));
            messageHelper.replyMys(sendMessage,msg);
        }else {
            userBO.getUserConfig().setTravel(userBO.getUserConfig().getTravel() + 50);
            int i = RandomUtil.randomInt(5, 15);
            sb.append("你花费了").append(i).append("天，采集了资源 [").append(xiuXianExploreResource.getResourceName()).append("]\n");
            exploreHelper.lockUser(exploreUser, days + i, userBO.getName() + "正在采集中");
        }

        if(flag){
            //战斗胜利或采集
            //雷之印掉落
            logger.info("资源信息为：{}",xiuXianExploreResource);
            int goldNum = RandomUtil.randomInt(1, xiuXianExploreResource.getRewardValue()) + exploreUser.getExploreMap() - 20;
            if(xiuXianExploreResource.getResourceName().equals("雷之印宝箱")){
                goldNum += 20;
            }
            exploreUser.setGoldNum(exploreUser.getGoldNum() + goldNum);
            sb.append("你获得了 [雷之印] * ").append(goldNum).append("\n");
            //物品掉落
            String drop_item = xiuXianExploreResource.getDropItem();
            logger.info("资源信息为：{}",drop_item);
            if(StrUtil.isNotBlank(drop_item)){
                String[] split = drop_item.split(",");
                String s = cn.hutool.core.util.RandomUtil.randomEle(split);
                String[] itemArr = s.split("\\*");
                int num = RandomUtil.randomInt(1, Integer.parseInt(itemArr[1]));
                itemHelper.addItem(userBO, itemArr[0], num);

                sb.append("你获得了 [").append(itemArr[0]).append("] * ").append(num).append("\n");
            }

            //资源数量减少
            xiuXianExploreResource.setNowNum(xiuXianExploreResource.getNowNum() - 1);
            userHelper.saveUserInfo(userBO);
            exploreHelper.updateUser(exploreUser);
            exploreHelper.updateResource(xiuXianExploreResource);
            messageHelper.replyMys(sendMessage,sb.toString());
        }
    }



}
